﻿Imports System.IO
Imports System.Net
Imports System.Text


Public Class Form2
    Property mo As String
    Property md As String
    Private Declare Function MessageBoxTimeout Lib "user32" Alias "MessageBoxTimeoutA" (ByVal hwnd As IntPtr, ByVal lpText As String, ByVal lpCaption As String, ByVal wType As UInteger, ByVal wlange As UInteger, ByVal dwTimeout As UInteger) As Integer

    Private Sub MsgBox(ByVal message As String, ByVal title As String)
        MessageBoxTimeout(Me.Handle, message, title, vbInformation, 0, 2000)
    End Sub
    Private Sub MsgBox(ByVal message As String)
        MsgBox(message, Application.ProductName)
    End Sub
    Private Sub Form2_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Rfid1.Close()
        Application.ExitThread()
    End Sub
    Private Sub SelectWo()
        If user.IsFirst Then
            Button1.Enabled = True
            Dim frm As New HDialog(user.ParentId)
            Dim result = frm.ShowDialog(Me)
            If result = DialogResult.OK Then
                Label2.Text = mo
                Label3.Text = md
            End If
        End If
    End Sub

    Private Sub LoadReading()
        Dim connStrList = Rfid1.GetDriverInfoList
        DrvBtn.DropDownItems.Clear()
        StatusLabel1.Text = "设备信息"
        StatusLabel1.ToolTipText = "点击刷新"
        For Each connStr In connStrList
            DrvBtn.DropDownItems.Add(connStr.First.Key)
        Next
        DrvBtn.Text = connStrList.FirstOrDefault().First().Key
        For Each ConnStr In connStrList.ToList
            Rfid1.Close()
            Rfid1.Connstr = ConnStr.First.Value
            Rfid1.Open()
            Threading.Thread.Sleep(500)
            If Rfid1.GetReaderInfor IsNot Nothing Then
                DrvBtn.Text = ConnStr.First.Key
                StatusLabel1.Text = Rfid1.GetReaderInfor
                StatusLabel1.ToolTipText = ConnStr.First.Value
                Exit For
            End If
        Next
    End Sub

    Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Call SelectWo()
        Call LoadReading()
    End Sub

    Private Sub Post_Product(userToken As Object)
        Try
            Dim client As New WebClient()
            AddHandler client.UploadDataCompleted, AddressOf ProductUpdateDataCallback
            AddHandler client.UploadProgressChanged, AddressOf uploadProgress
            Dim address As New Uri(Urls.API_PSAPI)
            Dim pass = New PostProduct With {
                .serialNumber = TextBox1.Text,
                .moNumber = mo,
                .modelName = md
            }
            Dim json As String = JsonClass.SerializeObjectToJson(pass)
            Dim data As Byte() = Encoding.UTF8.GetBytes(json)
            client.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
            client.Headers.Add("ContentLength", data.Length.ToString())
            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)")
            client.UploadDataAsync(address, "POST", data, userToken)


        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Sub

    ''' <summary>
    ''' 上线返回
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub ProductUpdateDataCallback(sender As Object, e As UploadDataCompletedEventArgs)
        Try
            Dim s As String = Encoding.UTF8.GetString(e.Result)
            Dim requestID As Integer = CType(e.UserState, Integer)
            Console.WriteLine(requestID)
            Console.WriteLine(s)

            Dim result As ProBingInfo = JsonClass.DeserializeJsonToObject(Of ProBingInfo)(s)
            If result Is Nothing Then
                Call SetState(TextBox1.Text)
                MsgBox(s)
                uidList.Remove(TextBox1.Text)
                DataGridView1.Rows.RemoveAt(requestID)
                TextBox1.Clear()
                Exit Sub
            End If
            Call Http_post(requestID)
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub


    ''' <summary>
    ''' 直接过站
    ''' </summary>
    ''' <param name="userToken"></param>
    Private Sub Http_post(userToken As Object)
        Try
            Dim client As New WebClient()
            AddHandler client.UploadDataCompleted, AddressOf updateDataCallback
            AddHandler client.UploadProgressChanged, AddressOf uploadProgress
            Dim address As New Uri(Urls.API_PDAPI)
            Dim pass = New PassProduct With {
                .serialNumber = TextBox1.Text,
                .employeeId = user.Id,
                .parentId = user.ParentId,
                .processingState = 0,
                .passStationTimes = 1
            }
            Dim json As String = JsonClass.SerializeObjectToJson(pass)

            Dim data As Byte() = Encoding.UTF8.GetBytes(json)
            client.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
            client.Headers.Add("ContentLength", data.Length.ToString())
            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)")

            client.UploadDataAsync(address, "POST", data, userToken)


        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try

    End Sub


    Private Sub OpenReadCallback(sender As Object, e As OpenReadCompletedEventArgs)

        Dim reader As New StreamReader(e.Result)
        Dim s As String = reader.ReadToEnd()
        Console.WriteLine(s)
        reader.Close()
    End Sub



    Private Sub updateDataCallback(sender As Object, e As UploadDataCompletedEventArgs)
        If e.Cancelled Then
            Console.WriteLine("取消")
        Else
            Try
                Dim s As String = Encoding.UTF8.GetString(e.Result)
                Dim requestID As Integer = CType(e.UserState, Integer)
                Console.WriteLine(requestID)
                Console.WriteLine(s)
                Call SetState(TextBox1.Text)
                Dim result As ResultProduct = JsonClass.DeserializeJsonToObject(Of ResultProduct)(s)
                If result Is Nothing Then
                    MsgBox(s)
                    uidList.Remove(TextBox1.Text)
                    DataGridView1.Rows.RemoveAt(requestID)
                    TextBox1.Clear()
                    Exit Sub
                End If
                DataGridView1.Rows(requestID).Cells(1).Value = result.serialNumber
                DataGridView1.Rows(requestID).Cells(2).Value = result.moNumber
                DataGridView1.Rows(requestID).Cells(3).Value = result.modelName
                DataGridView1.Rows(requestID).Cells(4).Value = result.inStationTime
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
        End If

    End Sub

    Private Sub SetState(ByVal uid As String)
        Dim wr = New WebRequestHelper
        Dim querydata As New Dictionary(Of String, String)
        querydata.Add("fid", uid)
        querydata.Add("pid", user.ParentId)

        Dim json = wr.HttpGet(Urls.API_PSDETAILS, querydata)
        Dim result = JsonClass.DeserializeJsonToObject(Of ProIOSum)(json)
        If result IsNot Nothing Then
            mo_value.Text = result.moNumber
            md_value.Text = result.modelName
            sum_value.Text = result.inputNumber
            count_value.Text = result.online
            my_value.Text = result.myParentCount
        End If
        Console.WriteLine(json)

        Dim json2 = wr.HttpGet(Urls.API_SCAN_RECORD, querydata)
        Dim result2 = JsonClass.DeserializeJsonToObject(Of List(Of ProRecords))(json2)
        If result2 IsNot Nothing Then
            Dim rr = result2.Select(Of Object)(Function(x) New With {
            .序列号 = x.serialNumber,
            .工单号 = x.moNumber,
            .物品名称 = x.modelName,
            .时间 = x.inStationTime,
            .扫描人 = x.userName,
            .部门 = x.department,
            .工序 = x.parentName
        }).ToList()
            DataGridView2.DataSource = Nothing
            DataGridView2.DataSource = rr
        End If
        Console.WriteLine(json2)


    End Sub


    Private Sub uploadProgress(sender As Object, e As UploadProgressChangedEventArgs)

        Dim requestID As Integer = CType(e.UserState, Integer)
        DataGridView1.Rows(requestID).Cells(5).Value = String.Format("{0}%", e.ProgressPercentage)
    End Sub




    Dim uidList As New HashSet(Of String)
    Private user As User
    Public Sub New(ByVal user As User)
        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。
        Me.user = user
        Me.Text = user.ParentName & " [" & user.Name & "]  --扫描"

    End Sub

    Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
        If TextBox1.TextLength = 0 Then
            Exit Sub
        End If
        Dim isAdd As Boolean = uidList.Add(TextBox1.Text)
        If isAdd Then
            DataGridView1.Rows.Add(1)
            Dim AddRowNum As Integer = DataGridView1.Rows.Count - 1
            DataGridView1.CurrentCell = DataGridView1.Rows(AddRowNum).Cells(0)
            DataGridView1.Rows(AddRowNum).Cells(0).Value = TextBox1.Text
            If user.IsFirst Then
                Call Post_Product(AddRowNum)
            Else
                Call Http_post(AddRowNum)
            End If
        Else
            For i As Integer = 0 To DataGridView1.Rows.Count - 1
                If TextBox1.Text = DataGridView1.Rows(i).Cells(0).Value Then
                    DataGridView1.CurrentCell = DataGridView1.Rows(i).Cells(0)
                    If DataGridView1.Rows(i).Cells(1).Value = String.Empty Then
                        If user.IsFirst Then
                            Call Post_Product(i)
                        Else
                            Call Http_post(i)
                        End If
                    End If
                    Exit For
                End If
            Next
        End If

    End Sub





    Private Sub DataGridView1_RowsAdded(sender As System.Object, e As DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded
        Label1.Text = DataGridView1.RowCount
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Call SelectWo()
    End Sub

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        Process.Start(Urls.URL_API_HOST)
    End Sub

    Private Sub DataGridView1_UserDeletedRow(sender As Object, e As DataGridViewRowEventArgs) Handles DataGridView1.UserDeletedRow
        uidList.Remove(e.Row.Cells(0).Value)
        TextBox1.Clear()
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Try
            If user.IsFirst Then
                user.IsFirst = False
                Button1.Enabled = False
            End If
            uidList.Remove(TextBox1.Text)
            uidList.Remove(DataGridView1.CurrentRow.Cells(0).Value.ToString())
            TextBox1.Clear()
        Catch ex As Exception

        End Try
    End Sub

    Private Sub DataGridView1_RowPostPaint(sender As Object, e As DataGridViewRowPostPaintEventArgs) Handles DataGridView1.RowPostPaint, DataGridView2.RowPostPaint
        Dim dgv = TryCast(sender, DataGridView)
        Dim SolidBrush = New SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor)
        If dgv.RowHeadersVisible Then
            Dim rec As New Rectangle(e.RowBounds.Left, e.RowBounds.Top, dgv.RowHeadersWidth, e.RowBounds.Height)
            Dim StrFormat As New StringFormat
            StrFormat.LineAlignment = StringAlignment.Center
            StrFormat.Alignment = StringAlignment.Far
            e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, SolidBrush, rec, StrFormat)
        End If
    End Sub
#Region "读卡器操作"


    'Property HexUID As Byte()
    Private Sub Rfid1_GetTabInfoEvent(sender As Object, e As RFIDLIB.RFIDEventArgs) Handles Rfid1.TabsEvent
        TextBox1.Text = e.UID
        If e.DataLenght Then
            Dim data = BitConverter.ToString(e.Data).Replace("-", String.Empty)
            Dim ddd = "Q" & Microsoft.VisualBasic.Left(data, 8) & "-" & Microsoft.VisualBasic.Mid(data, 13)
            TabsContent.Text = ddd
        End If

        'HexUID = e.UIDHEX
    End Sub


    Private Sub DrvBtn_DropDownItemClicked(sender As Object, e As ToolStripItemClickedEventArgs) Handles DrvBtn.DropDownItemClicked
        Dim connStrList = Rfid1.GetDriverInfoList
        Dim tr = TryCast(sender, ToolStripSplitButton)
        tr.Text = e.ClickedItem.Text
        Select Case tr.Name
            Case DrvBtn.Name
                Dim connStr As String = connStrList.FirstOrDefault(Function(x) x.ContainsKey(tr.Text)).First().Value
                Rfid1.Close()
                Threading.Thread.Sleep(500)
                Rfid1.Connstr = connStr
                Rfid1.Open()

                If Rfid1.GetReaderInfor IsNot Nothing Then
                    StatusLabel1.Text = Rfid1.GetReaderInfor
                    StatusLabel1.ToolTipText = connStr
                End If
        End Select
    End Sub

    Private Sub StatusLabel1_Click(sender As Object, e As EventArgs) Handles StatusLabel1.Click
        Call LoadReading()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    End Sub

    Private Sub ResetLabel_Click(sender As Object, e As EventArgs) Handles resetLabel.Click
        'Rfid1.SetGetConfig()
    End Sub
#End Region
End Class